package com.vista.producto;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;

import com.utilidades.CeldaRenderGeneral;

public class PanelBrowseTablaProducto extends JPanel {

	private static final Color rojo = new Color(255, 51, 0);
	private static final Color celeste = new Color(153, 204, 255);
	private static final Color naranja = new Color(255, 153, 0);

	private int coordX = 5, coordY = 5, cmbRowsPageWidth = 64, etiRowsPageWidth = 54;
	private int cmdPagWidth = 25, cmdPagHeigth = 25, marginLeft = 5, marginTop = 5;

	private int totalRows;
	private int rowsPage = 100;
	private int totalPage;
	private int visiblePages;
	private List listRows;
	private Map mapPages;
	private JButton[] cmdArrayPag;
	private JLabel etiInfo;
	private int iniItePag;
	private int iteCmd;
	private int iteIni;
	private int iteFin;
	private int idxPag;
	private int resto;
	private int numeroBoton;
	public ModeloTablaCtrlProducto modTabCtrlPrd;
	public JTable tabCtrlPrd;
	private CeldaRenderGeneral modTabCellRender;
	private DlgControlProducto dlgCtrlPrd;
	private JScrollPane scrTabCtrlPrd;
	private TableColumn[] colTabCtrlPrd;
	private JComboBox cmbRowsPage;
	private List listResult;
	private JLabel etiRowsPage;

	public PanelBrowseTablaProducto(DlgControlProducto dlgCtrlPrd, int left, int top, int width, int heigth) {

		this.dlgCtrlPrd = dlgCtrlPrd;
		super.setBorder(javax.swing.BorderFactory.createEtchedBorder());
		super.setLayout(null);
		super.setBounds(left, top, width, heigth);

		etiRowsPage = new JLabel("Reg x Pag");
		etiRowsPage.setBounds(width - (etiRowsPageWidth + marginLeft + cmbRowsPageWidth + marginLeft), coordY, 100, cmdPagHeigth);
		super.add(etiRowsPage);

		cmbRowsPage = new JComboBox();
		cmbRowsPage.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		cmbRowsPage.setFont(new Font("Tahoma", Font.PLAIN, 13));
		cmbRowsPage.addItem("100");
		cmbRowsPage.addItem("500");
		cmbRowsPage.addItem("1000");
		cmbRowsPage.addItem("5000");
		cmbRowsPage.addItem("10000");
		cmbRowsPage.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg0) {

				cmbRowsPageItemChanged(arg0);

			}
		});
		cmbRowsPage.setBounds(width - (cmbRowsPageWidth + marginLeft), coordY, cmbRowsPageWidth, cmdPagHeigth);
		super.add(cmbRowsPage);

		crearTablaPanel();

	}

	// @Override
	// public void paint(Graphics g) {
	// // super.setBorder(javax.swing.BorderFactory.createEtchedBorder());
	// // super.setLayout(null);
	// //
	// // crearTablaPanel();
	// //
	// // super.setOpaque(false);
	// // super.paint(g);
	// }// Fin de metodo de dibujad de Jpanel

	private void crearTablaPanel() {

		this.scrTabCtrlPrd = new JScrollPane();
		scrTabCtrlPrd.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		scrTabCtrlPrd.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

		this.tabCtrlPrd = new JTable();
		tabCtrlPrd.setFont(new Font("Tahoma", Font.PLAIN, 14));
		tabCtrlPrd.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

		this.scrTabCtrlPrd.setViewportView(this.tabCtrlPrd);
		super.add(this.scrTabCtrlPrd);
		this.scrTabCtrlPrd.setBounds(coordX, (coordY + marginTop + cmdPagHeigth), (getSize().width) - (marginLeft * 2), (getSize().height - marginTop - 35));

		/*
		 * Crear Modelo de Tabla
		 */
		this.modTabCtrlPrd = new ModeloTablaCtrlProducto();
		this.tabCtrlPrd.setModel(this.modTabCtrlPrd);
		this.modTabCellRender = new CeldaRenderGeneral();
		try {
			this.tabCtrlPrd.setDefaultRenderer(Class.forName("java.lang.String"), this.modTabCellRender);
			this.tabCtrlPrd.setDefaultRenderer(Class.forName("java.lang.Integer"), this.modTabCellRender);
			this.tabCtrlPrd.setDefaultRenderer(Class.forName("java.lang.Double"), this.modTabCellRender);
		} catch (ClassNotFoundException ex) {
			Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
		}

		this.tabCtrlPrd.setSelectionMode(1);
		this.tabCtrlPrd.getTableHeader().setReorderingAllowed(false);
		this.tabCtrlPrd.setAutoResizeMode(0);
		this.tabCtrlPrd.setShowGrid(true);

		String[] header = { "Area", "SubArea", "Cliente", "Modelo", "Tipo", "Articulo", "Color", "Talla", "Ficha", "Fecha", "Estado", "Pcs", "fic_cod", "subare_cod", "are_cod", "detped_cod", "ped_cod", "prd_cod", "gru_cod" };
		// String[] tipo = { "Date", "String", "String", "String", "String", "String", "String", "String", "Double", "String" };

		int[] ancho = { 90, 110, 180, 85, 95, 160, 90, 50, 45, 80, 100, 40, 0, 0, 0, 0, 0, 0, 0 };

		this.colTabCtrlPrd = new TableColumn[header.length];

		for (int iteHead = 0; iteHead < header.length; iteHead++) {
			this.colTabCtrlPrd[iteHead] = this.tabCtrlPrd.getColumn(header[iteHead]);
			this.colTabCtrlPrd[iteHead].setResizable(true);
			this.colTabCtrlPrd[iteHead].setPreferredWidth(ancho[iteHead]);
			// colTabCtrlPrd[iteHead].addPropertyChangeListener(new ListenerCambioPropiedad());

			if (ancho[iteHead] == 0) {
				this.tabCtrlPrd.getColumnModel().getColumn(iteHead).setMaxWidth(0);
				this.tabCtrlPrd.getColumnModel().getColumn(iteHead).setMinWidth(0);
				this.tabCtrlPrd.getTableHeader().getColumnModel().getColumn(iteHead).setMaxWidth(0);
				this.tabCtrlPrd.getTableHeader().getColumnModel().getColumn(iteHead).setMinWidth(0);
			}
		}
	}

	public void crearTablaResultado(List listResult) {

		this.listResult = listResult;
		if (listResult != null) {

			totalRows = listResult.size();
			visiblePages = 5;

			totalPage = totalRows / rowsPage;
			totalPage = (totalPage < 0) ? 0 : totalPage;
			visiblePages = (visiblePages < 0) ? 0 : visiblePages;
			resto = totalRows % rowsPage;
			totalPage = (resto > 0) ? totalPage + 1 : totalPage;
			if (totalPage <= visiblePages) {
				visiblePages = totalPage;
			}

			idxPag = 0;
			iniItePag = 0;

			if (cmdArrayPag != null) {
				for (int ite = 0; ite < cmdArrayPag.length; ite++) {
					remove(cmdArrayPag[ite]);
				}
			}

			crearBotonesPaginacion("");
			llenarMapaListas(listResult);
			fillRecordTable(idxPag);
			super.repaint();

		}// Fin de if(listResult != null)
	}

	public void llenarMapaListas(List listResult) {

		if (mapPages == null) {
			mapPages = new HashMap();
		}
		
		mapPages.clear();
		
		int iteRow = 0;
		int rowsTable = 0;
		String[] record;
		dlgCtrlPrd.totalPiezas = 0;
		for (int itePag = 0; itePag < totalPage; itePag++) {

			listRows = new ArrayList();
			rowsTable = (listResult.size() <= rowsPage) ? listResult.size() : rowsPage;

			for (int ite = 0; ite < rowsTable; ite++) {
				if (iteRow < listResult.size()) {

					record = ((String) listResult.get(iteRow)).split("#");

					listRows.add(listResult.get(iteRow));
					iteRow++;
					dlgCtrlPrd.totalPiezas = dlgCtrlPrd.totalPiezas + Integer.parseInt(record[11]);
				}
			}
			dlgCtrlPrd.txtTotalPiezas.setValue(dlgCtrlPrd.totalPiezas);
			mapPages.put(itePag, listRows);

		}
	}

	private void fillRecordTable(int idxPag) {

		setCurrentPage(idxPag);
		List listRows = (List) mapPages.get(idxPag);

		Object[] record = { "", "", "", "", "", "", "", "", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0 };
		this.modTabCtrlPrd.setRowCount(0);
		// this.modTabCtrlPrd.setRowCount(listRows.size());
		int numIte = 0;
		int total = 0;
		boolean agregar = true;
		if (listRows != null && listRows.size() > 0) {
			for (int ite = 0; ite < listRows.size(); ite++) {

				String[] regTab = ((String) listRows.get(ite)).split("#");
				int valor = Integer.parseInt(regTab[17]);
				dlgCtrlPrd.man.tal.setObjeto(dlgCtrlPrd.man.obtenerItemListaProductoGeneral(Integer.parseInt(regTab[17])));
				dlgCtrlPrd.man.mod.setObjeto(dlgCtrlPrd.man.obtenerItemListaProductoGeneral(dlgCtrlPrd.man.tal.getPrd_supuno()));
				dlgCtrlPrd.man.prd.setObjeto(dlgCtrlPrd.man.obtenerItemListaProductoGeneral(dlgCtrlPrd.man.tal.getPrd_supdos()));
				dlgCtrlPrd.man.are.setObjeto(dlgCtrlPrd.man.obtenerItemListaArea(Integer.parseInt(regTab[0])));
				dlgCtrlPrd.man.subAre.setObjeto(dlgCtrlPrd.man.obtenerItemListaSubArea(Integer.parseInt(regTab[1])));

				if (dlgCtrlPrd.chkUltimo.isSelected() && (ite + 1) < listRows.size()) {
					agregar = false;
				} else {
					agregar = true;
				}
				if (agregar) {

					this.modTabCtrlPrd.addRow(record);
					this.modTabCtrlPrd.setValueAt(dlgCtrlPrd.man.are.getAre_nom(), numIte, 0); // String
					this.modTabCtrlPrd.setValueAt(dlgCtrlPrd.man.subAre.getSubare_nom(), numIte, 1); // String
					this.modTabCtrlPrd.setValueAt(regTab[2], numIte, 2); // String
					this.modTabCtrlPrd.setValueAt(dlgCtrlPrd.man.mod.getPrd_ide(), numIte, 3); // String
					this.modTabCtrlPrd.setValueAt(regTab[4], numIte, 4); // String
					this.modTabCtrlPrd.setValueAt(dlgCtrlPrd.man.prd.getPrd_ide(), numIte, 5); // String
					this.modTabCtrlPrd.setValueAt(regTab[6], numIte, 6); // String
					this.modTabCtrlPrd.setValueAt(dlgCtrlPrd.man.tal.getPrd_des(), numIte, 7); // String
					this.modTabCtrlPrd.setValueAt(regTab[8], numIte, 8); // String
					this.modTabCtrlPrd.setValueAt(dlgCtrlPrd.man.funUsu.dateToString(dlgCtrlPrd.man.funUsu.stringToDateSql(regTab[9]), "dd/MM/yyyy"), numIte, 9); // String Fecha de Ingreso
					this.modTabCtrlPrd.setValueAt(regTab[10], numIte, 10); // String
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[11]), numIte, 11); // Integer
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[12]), numIte, 12); // Integer
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[13]), numIte, 13); // Integer
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[14]), numIte, 14); // Integer
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[15]), numIte, 15); // Integer
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[16]), numIte, 16); // Integer
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[17]), numIte, 17); // Integer
					this.modTabCtrlPrd.setValueAt(Integer.parseInt(regTab[18]), numIte, 18); // Integer

					total = total + Integer.parseInt(regTab[11]);
					numIte++;
				}
			}
			dlgCtrlPrd.txtPiezasPagina.setValue(total);
		}// Fin d e if (listRows != null && listRows.size() > 0) {
	}

	public void crearBotonesPaginacion(String mover) {

		if (mover.equals("adelante")) {
			if ((idxPag + visiblePages) < totalPage) {
				this.idxPag++;
			}
		} else if (mover.equals("atras")) {
			if ((idxPag) > 0) {
				this.idxPag--;
			}
		} else {
			this.idxPag = idxPag;
		}

		numeroBoton = visiblePages;
		iniItePag = idxPag;
		iteCmd = 0;
		iteIni = 0;
		iteFin = visiblePages;
		if (totalPage > visiblePages) {
			numeroBoton = visiblePages + 2;
		}

		cmdArrayPag = new JButton[numeroBoton];

		if (totalPage > visiblePages) {

			coordX = (iteCmd * cmdPagWidth) + marginLeft;

			cmdArrayPag[0] = crearBoton(coordX, coordY, cmdPagWidth, cmdPagHeigth, -1);
			super.add(cmdArrayPag[0]);
			iteIni++;
			iteFin++;
			iteCmd++;
		}

		for (int ite = iteIni; ite < iteFin; ite++) {

			coordX = (iteCmd * cmdPagWidth) + marginLeft;
			cmdArrayPag[ite] = crearBoton(coordX, coordY, cmdPagWidth, cmdPagHeigth, iniItePag);
			super.add(cmdArrayPag[ite]);
			iteCmd++;
			iniItePag++;

		}
		if (totalPage > visiblePages) {
			coordX = (iteCmd * cmdPagWidth) + marginLeft;
			cmdArrayPag[iteCmd] = crearBoton(coordX, coordY, cmdPagWidth, cmdPagHeigth, iteCmd);
			super.add(cmdArrayPag[iteCmd]);
			iteCmd++;
		}

		if (etiInfo == null) {
			etiInfo = new JLabel();
			super.add(etiInfo);
		}
		coordX = (iteCmd * cmdPagWidth) + marginLeft;
		etiInfo.setBounds(coordX + marginLeft, coordY, 400, cmdPagHeigth);
		etiInfo.setText("Total Paginas : " + totalPage + " Total Registros : " + totalRows + " Registros por Pagina : " + rowsPage);

	}

	public JButton crearBoton(int coordX, int coordY, int cmdPagWidth, int cmdHeight, int parIndex) {

		JButton cmdPag = new JButton();
		cmdPag.setBounds(coordX, coordY, cmdPagWidth, cmdHeight);
		String nombreBoton = "";
		if (totalPage > visiblePages) {
			if (parIndex == -1) {
				nombreBoton = "atras_0";
				cmdPag.setText("<<");
			} else if (iteCmd == visiblePages + 1) {
				nombreBoton = "adelante_0";
				cmdPag.setText(">>");
			} else {
				nombreBoton = "cmdArrayPag_" + String.valueOf(parIndex);
				cmdPag.setText(String.valueOf(parIndex + 1));
			}
		} else {
			nombreBoton = "cmdArrayPag_" + String.valueOf(parIndex);
			cmdPag.setText(String.valueOf(parIndex + 1));
		}

		cmdPag.setName(nombreBoton);
		cmdPag.setActionCommand(nombreBoton);
		cmdPag.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		cmdPag.setBounds(coordX, coordY, cmdPagWidth, cmdHeight);
		cmdPag.setForeground(naranja);
		// cmdPag.setBackground(colorFondo);
		// cmdPag.setForeground(colorTexto);
		cmdPag.setMargin(new java.awt.Insets(0, 0, 0, 0));
		cmdPag.addActionListener(new cmdArrayPagListener(this));

		return cmdPag;
	}// Fin de Metodo para crear botones de dias de calendario

	public void setCurrentPage(int currentPage) {
		for (int ite = 0; ite < numeroBoton; ite++) {
			cmdArrayPag[ite].setForeground(naranja);
			String[] valCmd = cmdArrayPag[ite].getName().split("_");
			if (!valCmd[0].equals("atras") && !valCmd[0].equals("adelante")) {
				if ((Integer.parseInt(valCmd[1])) == currentPage) {
					cmdArrayPag[ite].setForeground(rojo);
				}
			}
		}
		idxPag = currentPage;
	}

	public ModeloTablaCtrlProducto getModTabCtrlPrd() {
		return modTabCtrlPrd;
	}

	public JTable getTabCtrlPrd() {
		return tabCtrlPrd;
	}

	private void cmbRowsPageItemChanged(ItemEvent arg0) {

		if (this.listResult != null) {
			rowsPage = Integer.parseInt(cmbRowsPage.getSelectedItem().toString());
			crearTablaResultado(this.listResult);
		}
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {

				DlgControlProducto frame = new DlgControlProducto(null);
				PanelBrowseTablaProducto panelBrowseTablaProducto = new PanelBrowseTablaProducto(frame, 10, 223, 795, 391);

				frame.setLayout(null);
				frame.setSize(850, 600);
				frame.add(panelBrowseTablaProducto);
				frame.setVisible(true);

			}
		});
	}

	/*
	 * LISTENER DE CLICK
	 */
	private static class cmdArrayPagListener implements ActionListener {

		PanelBrowseTablaProducto panelPagina;

		public cmdArrayPagListener(PanelBrowseTablaProducto panelPagina) {
			this.panelPagina = panelPagina;
		}

		@Override
		public void actionPerformed(ActionEvent e) {

			JButton objCmd = (JButton) e.getSource();
			String[] valCmd = objCmd.getActionCommand().split("_");
			if (valCmd[0].equals("atras") || valCmd[0].equals("adelante")) {

				if (panelPagina.cmdArrayPag != null) {
					for (int ite = 0; ite < panelPagina.cmdArrayPag.length; ite++) {
						panelPagina.remove(panelPagina.cmdArrayPag[ite]);
					}
					panelPagina.repaint();
//					panelPagina.update(panelPagina.getGraphics());
					panelPagina.crearBotonesPaginacion(valCmd[0]);

				}

			} else {
				int idxPag = Integer.parseInt(valCmd[1]);
				panelPagina.fillRecordTable(idxPag);
			}
			// System.out.println("bootn : " + objCmd.getActionCommand());
		}// Fin de Action performed del boton de la palanca
	}// fin de la clase estatica para escuchar las acciones de los botones de palanca
}
